package com.suyundeng.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suyundeng.entity.JsonResult;
import com.suyundeng.entity.SUser;
import com.suyundeng.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hhx
 * @since 2021-04-12
 */
@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ResponseBody
    @GetMapping("/users")
    public JsonResult getPage(@RequestParam(value = "current",required = false,defaultValue = "1")Integer current){

        try{
            Page<SUser> page = new Page<>(current,10);
            IPage<SUser> data = userService.getPage(page);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }

    @ResponseBody
    @DeleteMapping("/user/{id}")
    public JsonResult deleteUser(@PathVariable("id") String id){

        try{
            boolean data = userService.removeById(id);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }

    @ResponseBody
    @PostMapping("/user")
    public JsonResult addUser(@RequestBody SUser user){

        try{
            user.setPassWord(passwordEncoder.encode(user.getPassWord()));
            boolean data = userService.save(user);
            //添加基础权限

            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }

    @ResponseBody
    @PutMapping("/user")
    public JsonResult modifyUser(@RequestBody SUser user){

        try{
            user.setPassWord(passwordEncoder.encode(user.getPassWord()));
            boolean data = userService.updateById(user);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }


}
